package com.dayuanit.dy17.atm.controller;

import com.dayuanit.dy17.atm.captcha.GifCaptcha;
import com.dayuanit.dy17.atm.config.AtmPropertiesConfig;
import com.dayuanit.dy17.atm.dto.ResponseDTO;
import com.dayuanit.dy17.atm.entity.User;
import com.dayuanit.dy17.atm.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;

    @RequestMapping(value = "/user/uploadAvatar")
    public ResponseDTO uploadAvatar(MultipartFile avatarFile, HttpSession session) {
        if (avatarFile.isEmpty()) {
            return ResponseDTO.fail("请选择头像");
        }

        try {
            //方案一：
//            FileOutputStream fos = new FileOutputStream("D:/dayuanit/17/avatar/xxx.png");
//            InputStream is = avatarFile.getInputStream();
//            byte[] buff = new byte[1024];
//            int length = -1;
//            while (-1 != (length = is.read(buff))) {
//                fos.write(buff, 0, length);
//                fos.flush();
//            }


//            Properties properties = new Properties();
//            properties.load(this.getClass().getClassLoader().getResourceAsStream("atm.properties"));
//            String avatarPath = properties.getProperty("avatar.picture.path");
//
//            System.out.println(">>>>>>avatarPath=" + avatarPath);

            //方案二：
            avatarFile.transferTo(new File(atmPropertiesConfig.getAvatarPath() + getUserId(session)));

            return ResponseDTO.success();
        } catch (IOException e) {
            return ResponseDTO.fail("上传失败");
        }
    }

    @GetMapping("/user/showAvatar")
    public void showAvatar(HttpServletResponse response, HttpSession session) {
        try (FileInputStream fis = new FileInputStream(atmPropertiesConfig.getAvatarPath() + getUserId(session));) {
            ServletOutputStream outputStream = response.getOutputStream();
            int length = -1;
            byte[] buff = new byte[1024];
            while (-1 != (length = fis.read(buff))) {
                outputStream.write(buff, 0, length);
                outputStream.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/user/login", method = RequestMethod.POST)
    public ResponseDTO login(HttpServletRequest request, HttpSession session, String username, String password, String code) {

        System.out.println(">>>>>>>>>>>>>>>>>server name:" + atmPropertiesConfig.getServerName());

        //TODO 校验码正确 则调用service
        String originCode = (String)request.getSession().getAttribute("code");
        if (!originCode.equalsIgnoreCase(code)) {
            return ResponseDTO.fail("校验码错误");
        }

        User user = userService.login(username, password);
        session.setAttribute(login_user, user);

        //将session对象的保存的属性删除
        request.getSession().removeAttribute("code");
        return ResponseDTO.success();
    }

    @RequestMapping(value = "/user/register", method = RequestMethod.POST)
    public ResponseDTO register(String username, String password, String confirmPassword) {
        userService.register(username, password, confirmPassword);
        return ResponseDTO.success();
    }

    @RequestMapping(value = "/user/logout")
    public ResponseDTO logout(HttpSession session) {
        session.invalidate();
        return ResponseDTO.success();
    }

    @RequestMapping(value = "/user/createCaptcha")
    public void createCaptcha(HttpServletResponse response, HttpServletRequest request) {
        GifCaptcha gifCaptcha = new GifCaptcha();
        try {
            gifCaptcha.out(response.getOutputStream());
            String code = gifCaptcha.text();
            System.out.println("code=" + code);

            request.getSession().setAttribute("code", code);

            System.out.println(">>>request Code=" + request.getSession().getAttribute("code"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/user/resetPassword")
    public ResponseDTO resetPassword(String password, String confimPwd, HttpSession session) {
        System.out.println("---password=" + password + " confimPwd=" + confimPwd);

        String bindEmail = (String)session.getAttribute("bindEmail");
        String sign = (String)session.getAttribute("bindEmailSign");
        long createTime = (long)session.getAttribute("createTime");

        userService.resetPwd(password, confimPwd, bindEmail, sign, createTime);
        return ResponseDTO.success();
    }
}
